/***
 * 编写人：田光辉
 * 日期：2013-09-02
 */
document.write('<link rel="stylesheet" type="text/css" href="common/js/jquery-ui-multiselect/jquery.multiselect.css" />');
document.write('<link rel="stylesheet" type="text/css" href="common/js/jquery-ui-1.10.4.custom/css/cupertino/jquery-ui-1.10.4.custom.min.css"/>');
document.write('<script src="common/js/jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.min.js"></script>');
document.write('<script src="common/js/jquery-ui-multiselect/jquery.multiselect.js"></script>');

$(function(){
 //判断页面是否有需要异步加载的select，如果有则调用填充select方法
   if($("select").length>0){
      $("select").each(function(i){
    	  //请求数据源
         var datasource = $(this).attr("datasource");
         //请求参数
         var dataArgs = $(this).attr("dataargs");
       //请求参数
         var value = $(this).attr("data-v");
         //如果数据源不为空则发起请求
         if(datasource != undefined ){
        	 //判断是否是级联select如果不是则初始化Select并绑定change事件，如果是则值绑定change事件
            if($(this).attr("cascadeto") == undefined){
            	//绑定数据
                getSelectDatasource(datasource,value,dataArgs,$(this));
               $(this).change(function(){
            	   changeSelect($(this));
               });
            }else{
            	$(this).change(function(){
             	   changeSelect($(this));
                });
            }
         }
	  });
   }
});

/**
 * 给指定select绑定change事件方法
 * @param sel 目标Select组件
 */
function changeSelect(sel){
	var caseSelect = $("[cascadeto='"+sel.attr("id")+"']");
	//判断该组件是不是有级联绑定，如果有则触发，无则返回
	if(caseSelect.length == 1){
		var sval = sel.find("option:selected").val();
	    datasource = caseSelect.attr("datasource");
	    var cascade = caseSelect.attr("dataargs");
	    dataArgs =cascade.substring(0,cascade.indexOf(":")+1)+"'"+sval+"'";
	    
	    var value = caseSelect.attr("data-v");
	    getSelectDatasource(datasource,value,dataArgs,caseSelect);
	}else{
		return;
	}
}

/**
 * 清除级联Select组件的Options
 * @param selects 目标Select组件
 */
function clearOptions(selects){
	selects.find("option:not(:eq(0))").remove();
	var caseSelect = $("[cascadeto='"+selects.attr("id")+"']");
	if(caseSelect.length == 1){
		clearOptions(caseSelect);
	}
}

function isInArray(vals,val){
	if(null == vals || vals.length == 0){
		return -1;
	}
	return $.inArray(val.toString(), vals); 
	
}

/**
 * 请求数据并绑定指定select
 * @param actionUrl 请求数据源
 * @param dataArgs  请求参数
 * @param selects   绑定目标select组件
 */
function getSelectDatasource(datasource,value,dataArgs,selects){ 
  clearOptions(selects);
  var datas = "";
  if(dataArgs != undefined && dataArgs != ""){
	  datas = eval("({"+dataArgs+"})");
  }
  
  var loadingIndex = layer.msg('正在加载数据..', {shade:0.00001,icon: 16,time: 1000*60*10 });
  $.ajax({type:"POST", url:datasource,cache:false, dataType:"json", data:datas, success:function (data) {
      if(data != null && data!=""){
    	  if(data == "1"){
         	 location.href = getRootPath() + "/login.jsp";
          }else{
			  var options = new Array();
			  
			  var vals = null;
			  if(null != value && "" != value && value.length > 0){
				  vals = value.split(',');
			  }
      	      $.each(data,function(i,val){
      	    	  var selStr = "";
      	    	  if(undefined != value && null != value){
      	    		  selStr = isInArray(vals,val[selects.attr("sid")])!=-1?"selected=\"selected\"":"";
      	    	  }
      	         options.push("<option value=\""+val[selects.attr("sid")]+"\" "+selStr+">"+val[selects.attr("stext")]+"</option>");
      	      });
      	      selects.append(options.join(""));
      	      
      	      var multiple = false;
      	      if(selects.hasClass("Tselect")){
      	    	  if(selects.attr("multiple") == "multiple"){
      	    		multiple = true;
      	    	  }
	      	    	selects.multiselect({
	      	    		multiple:multiple,
	      	    		checkAllText:'全选',
	      	    		uncheckAllText:'取消全选',
	      	    		noneSelectedText:'请选择..',
	      	    		minWidth:'80%',
	          			selectedList: 20
	          		});
      	      }
      	    
          }
      }
      layer.close(loadingIndex);
  },error:function(){layer.close(loadingIndex);}});
}